Wrapper AutoBoxing Unboxing
A Wrapper class is a class that converts a primitive data type into an object. Each primitive type has a corresponding wrapper class.
| Primitive Data Type | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
int num = 1098; Integer obj = Integer.valueOf(num); // Manual wrapping System.out.println(obj);
Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper object by the Java compiler.
int a = 20; Integer obj = a; // Autoboxing System.out.println(obj);
Unboxing is the automatic conversion of a wrapper object into its corresponding primitive data type.
Integer obj = 30; int a = obj; // Unboxing System.out.println(a);
public class WrapperExample {
public static void main(String[] args) {
// Autoboxing
int x = 100;
Integer obj = x;
// Unboxing
Integer y = 200;
int num = y;
System.out.println("Autoboxing: " + obj);
System.out.println("Unboxing: " + num);
}
}